package cn.com.cym.gamezao.web.authorize;

import cn.com.cym.gamezao.annotation.AccessLimit;
import cn.com.cym.gamezao.annotation.AuthToken;
import cn.com.cym.gamezao.base.ResultResponse;
import cn.com.cym.gamezao.base.SearchPage;
import cn.com.cym.gamezao.dto.UserDto;
import cn.com.cym.gamezao.dto.UserPasswordDto;
import cn.com.cym.gamezao.dto.UserRegisterDto;
import cn.com.cym.gamezao.dto.UserResponse;
import cn.com.cym.gamezao.entity.LocalFile;
import cn.com.cym.gamezao.entity.authorize.User;
import cn.com.cym.gamezao.entity.authorize.UserInfo;
import cn.com.cym.gamezao.enums.UserType;
import cn.com.cym.gamezao.exception.BaseException;
import cn.com.cym.gamezao.service.LocalFileService;
import cn.com.cym.gamezao.service.authorize.UserService;
import cn.com.cym.gamezao.util.CommonUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Api(tags = "a-用户")
@RestController
@RequestMapping(value = "user")
public class UserController {

    final UserService thisService;

    final LocalFileService localFileService;

    public UserController(UserService userService,LocalFileService localFileService){
        this.thisService=userService;
        this.localFileService=localFileService;
    }

    @ApiImplicitParam(name = "id", value = "id", required = true,dataType = "Long")
    @ApiOperation(value = "根据id获取用户信息！")
    @ApiOperationSupport(order = 2, author = "mr.chen")
    @GetMapping("/{id}")
    @AuthToken
    public ResponseEntity<?> fetchOne(@PathVariable("id") Long id){
        final User user = thisService.fetchOne(id);
        return ResponseEntity.ok(user);
    }

    @ApiImplicitParam(name = "user", value = "user",dataType = "User", required = true)
    @ApiOperation(value = "新建用户信息！")
    @ApiOperationSupport(order = 1, author = "mr.chen")
    @PostMapping("")
    @AuthToken(userType = UserType.MANAGER)
    public ResponseEntity<?> save(@RequestBody User user){
        thisService.save(user);
        return ResponseEntity.ok(user);
    }


    @ApiImplicitParams(
            {@ApiImplicitParam(name = "id", value = "id",paramType = "path", required = true,dataType = "Long"),
                    @ApiImplicitParam(name = "user", value = "user",paramType = "body", required = true,dataType = "User")})
    @ApiOperation(value = "更新用户信息！")
    @ApiOperationSupport(order = 3, author = "mr.chen")
    @PutMapping("/{id}")
    @AuthToken
    public ResponseEntity<?> update(@RequestBody User user, @PathVariable("id") Long id){

        return thisService.fetchById(id).map(currentGameUser->{
                    BeanUtils.copyProperties(user,currentGameUser);
                    thisService.save(currentGameUser);
                    return ResponseEntity.ok(currentGameUser);
                })
                .orElseThrow(()->new BaseException("更新用户不存在",new ResultResponse("更新用户不存在", HttpStatus.BAD_REQUEST.value())));
    }

    @ApiImplicitParam(name = "searchPage", value = "searchPage", required = true,dataType = "SearchPage")
    @ApiOperation(value = "分页显示page！")
    @ApiOperationSupport(order = 4, author = "mr.chen")
    @PostMapping("/page")
    @AuthToken
    public ResponseEntity<?> page(@RequestBody SearchPage searchPage){
        Page<?> byPageable = this.thisService.findByPageable(searchPage);
        return ResponseEntity.ok(byPageable);
    }

    @ApiImplicitParam(name = "id", value = "id", required = true,dataType = "Long")
    @ApiOperation(value = "删除用户！")
    @ApiOperationSupport(order = 5, author = "mr.chen")
    @DeleteMapping("/{id}")
    @AuthToken
    public ResponseEntity<?> delete(@PathVariable("id") Long id){

        return this.thisService.fetchById(id).map(user -> {
                    this.thisService.logicDelete(id);
                    return ResponseEntity.ok(new ResultResponse("删除成功",HttpStatus.OK.value()));
                })
                .orElseThrow(()->new BaseException("数据不存在",new ResultResponse("数据不存在",HttpStatus.NOT_FOUND.value())));
    }


    @ApiImplicitParam(name = "id集合", value = "ids", required = true,dataType = "java.util.List")
    @ApiOperation(value = "批量删除用户！")
    @ApiOperationSupport(order = 6, author = "mr.chen")
    @DeleteMapping("")
    @AuthToken
    public ResponseEntity<?> deleteAll(@RequestBody List<Long> ids){
        final int i = this.thisService.deleteIds(ids, true);
        return  ResponseEntity.ok(new ResultResponse("批量删除成功,成功"+i+"条，失败"+(ids.size()-i)+"条",HttpStatus.OK.value()));
    }

    /**
     * 用户登录
     * @return 用户信息
     */
    @ApiImplicitParam(name = "userDto", value = "userDto", required = true,dataType = "UserDto")
    @ApiOperation(value = "用户登录")
    @ApiOperationSupport(order = 7, author = "mr.chen")
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserDto userDto){
        final UserResponse login = thisService.login(userDto);
        return ResponseEntity.ok(login);
    }


    /**
     * 用户登录
     * @return 用户信息
     */
    @ApiImplicitParam(name = "userDto", value = "userDto", required = true,dataType = "UserDto")
    @ApiOperation(value = "客户登录")
    @ApiOperationSupport(order = 7, author = "mr.chen")
    @PostMapping("/appLogin")
    public ResponseEntity<?> appLogin(@RequestBody UserDto userDto){
        final UserResponse login = thisService.login(userDto,true);
        return ResponseEntity.ok(login);
    }

    /**
     * 用户退出
     * @return 状态
     */
    @ApiOperation(value = "用户退出")
    @ApiOperationSupport(order = 9, author = "mr.chen")
    @DeleteMapping("/logout")
    @AuthToken
    public ResponseEntity<?> logout(){
        this.thisService.logout();
        return ResponseEntity.ok(new ResultResponse("退出成功",HttpStatus.OK.value()));
    }

    /**
     * 用户注册
     * @param user user
     * @return userResponse
     */
    @ApiImplicitParam(name = "user", value = "user", required = true,dataType = "User")
    @ApiOperation(value = "用户注册")
    @ApiOperationSupport(order = 10, author = "mr.chen")
    @PostMapping("/register")
    @AccessLimit
    public ResponseEntity<?> register(@RequestBody UserRegisterDto user){
        // 判断密码和验证密码是否一致
        if(CommonUtils.isEmpty(user.getPassword()) || !user.getPassword().equals(user.getSecPassword())){
            throw new BaseException("两次输入密码不一致",new ResultResponse("两次输入密码不一致",HttpStatus.BAD_REQUEST.value()));
        }
        User user1=new User();
        user1.setUserName(user.getUserName());
        user1.setEmail(user.getEmail());
        user1.setPassword(user.getPassword());
        user1.setTel(user.getTel());

        user1.setUserInfo(user.getUserInfo());

        //只允许注册应聘账号
        user1.setUserType(UserType.APPLICANT);
        //取消注册
        final UserResponse register = this.thisService.register(user1);

        return ResponseEntity.ok(register);
        //throw new BaseException("此功能关闭",new ResultResponse("不在提供注册功能",HttpStatus.BAD_REQUEST.value()));
    }

    /**
     * 修改密码 设置4小时只能修改一次
     * @param userPasswordDto userPasswordDto
     * @return userResponse
     */
    @ApiImplicitParam(name = "userPasswordDto", value = "userPasswordDto", required = true,dataType = "UserPasswordDto")
    @ApiOperation(value = "用户修改密码")
    @ApiOperationSupport(order = 11, author = "mr.chen")
    @PostMapping("/alterPassword")
    @AuthToken
    @AccessLimit(dateRange=4*60*60000L,limitCount=2)
    public ResponseEntity<?> alterPassword(@RequestBody UserPasswordDto userPasswordDto){
        final UserResponse userResponse = thisService.alterPassword(userPasswordDto);
        return ResponseEntity.ok(userResponse);
    }
}
